<template>
	<view class="container">
		<u-search :showAction="true" actionText="搜索" :animation="true" :clearabled="true" placeholder="请输入姓名"
			v-model="keyword" @custom="performSearch()" @clear="onClear()"></u-search>
		<view class="action-buttons">
			<u-button type="error" @click="deleteDialog=true">删除数据</u-button>
			<u-button type="primary" @click="importDialog=true">数据导入</u-button>
		</view>
		<!-- 弹出层 -->
		<u-popup :show="deleteDialog" mode="center" border-radius="10">
			<view style="padding: 20px; width: 80%; max-width: 400px; background-color: #fff;">
				<u--form labelPosition="left" ref="importForm">
					<u-form-item label="指定周数" borderBottom>
						<u--input v-model="deleteWeek" placeholder="请输入第几周(数字)"></u--input>
					</u-form-item>
				</u--form>
				<div style="display: flex; justify-content: space-between;">
					<u-button type="primary" text="确认" @click="showDeleteConfirm()"
						style="flex: 1; margin-right: 10px;"></u-button>
					<u-button color="#c8c9cc" text="取消" @click="deleteDialog=false" style="flex: 1;"></u-button>
				</div>
			</view>
		</u-popup>
		<!-- 弹出层 -->
		<u-popup :show="importDialog" mode="center" border-radius="10">
			<view style="padding: 20px; width: 80%; max-width: 400px; background-color: #fff;">
				<u--form labelPosition="left" :model="importLink" ref="importForm">
					<u-form-item label="链接" borderBottom>
						<u--input v-model="importLink.url" placeholder="请输入链接"></u--input>
					</u-form-item>
					<u-form-item label="周数" borderBottom>
						<u--input v-model="importLink.week" placeholder="请输入第几周(数字)"></u--input>
					</u-form-item>
				</u--form>
				<div style="display: flex; justify-content: space-between;">
					<u-button type="primary" text="确认" @click="confirmImport()"
						style="flex: 1; margin-right: 10px;"></u-button>
					<u-button color="#c8c9cc" text="取消" @click="importDialog=false" style="flex: 1;"></u-button>
				</div>
			</view>
		</u-popup>

		<uni-table ref="table" border stripe emptyText="暂无更多数据">
			<!-- 表头 -->
			<uni-tr>
				<uni-th width="50" align="center">操作</uni-th>
				<uni-th width="50" align="center">学号</uni-th>
				<uni-th width="100" align="center">姓名</uni-th>
				<!-- 动态生成每周的表头 -->
				<uni-th v-for="week in weeks" :key="'header-' + week" :width="100" align="center">
					第{{ week }}周 成绩/排名
				</uni-th>
			</uni-tr>

			<!-- 数据行 -->
			<uni-tr v-for="(student, index) in students" :key="'row-' + student.student_id">
				<uni-td>
					<view class="uni-group">
						<button class="uni-button" size="mini" type="default" @click="goPerson(student)">Go</button>
					</view>
				</uni-td>
				<uni-td align="center">{{ student.student_id }}</uni-td>
				<uni-td align="center">{{ student.name }}</uni-td>

				<!-- 对于每个学生，动态生成每周的成绩和排名 -->
				<uni-td v-for="week in weeks" :key="'cell-' + student.student_id + '-week-' + week" align="center">
					<view>成绩: {{ getScore(student.weeks, week) }}</view>
					<!-- <view>排名: {{ getRanking(student.weeks, week) }}</view> -->
					<view>排名: {{ getRanking(student.weeks, week) }}</view>
				</uni-td>
			</uni-tr>
		</uni-table>
		<u-popup :show="formDialog" :round="10" mode="center" style="width: 80%; max-width: 500px; padding: 20px;">
			<!-- 表单组件 -->
			<u--form labelPosition="left" :model="studenInfo" :rules="rules" ref="uForm"
				style="padding: 20px; background-color: #fff; border-radius: 10px;">
				<u-form-item label="姓名" prop="name" borderBottom style="margin-bottom: 20px;">
					<u--input v-model="studenInfo.name" border="none"></u--input>
				</u-form-item>
				<u-form-item v-if="insertDialog" label="学号" prop="student_id" borderBottom style="margin-bottom: 20px;">
					<u--input v-model="studenInfo.student_id" border="none"></u--input>
				</u-form-item>
				<u-form-item v-else label="学号" prop="student_id" borderBottom style="margin-bottom: 20px;">
					<u--input v-model="studenInfo.student_id" border="none" disabled></u--input>
				</u-form-item>
				<u-form-item label="班级" prop="class" borderBottom style="margin-bottom: 20px;">
					<u--input v-model="studenInfo.class" border="none"></u--input>
				</u-form-item>
				<div style="display: flex; justify-content: space-between;">
					<u-button v-if="insertDialog" type="primary" text="提交" @click="addStudent()"
						style="flex: 1; margin-right: 10px;"></u-button>
					<u-button v-else type="success" text="修改" @click="editStudent()"
						style="flex: 1; margin-right: 10px;"></u-button>
					<u-button color="#c8c9cc" text="取消" @click="formDialog=false" style="flex: 1;"></u-button>
				</div>
			</u--form>
		</u-popup>
	</view>
</template>
<script>
	import * as XLSX from 'xlsx'; // 引入 xlsx 库
	export default {
		data() {
			return {
				keyword: '',
				students: [], // 学生列表
				weeks: [],
				importDialog: false, //导入
				deleteDialog: false, //删除框
				deleteWeek: '',
				importLink: {
					url: '',
					week: ''
				},
				// 数据总量
				total: 0,
				loading: false,
				// 表单组件
				formDialog: false,
				insertDialog: true,
				studenInfo: {
					name: '',
					student_id: '',
					week: '',
					score: ''
				},
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请填写姓名（汉字）',
						trigger: ['blur', 'change']
					},
					'student_id': {
						type: 'number',
						required: true,
						message: '请填写学号（数字）',
						trigger: ['blur', 'change']
					},
					'class': {
						type: 'string',
						required: true,
						message: '请填写班级',
						trigger: ['blur', 'change']
					},
				},

			};
		},
		onLoad() {
			this.getData()
		},
		methods: {
			// 确认删除第几周
			showDeleteConfirm(studentId) {
				uni.showModal({
					title: '提示',
					content: '确定要删除第' + this.deleteWeek + '周数据吗？',
					success: (res) => {
						if (res.confirm) {
							this.confirmDelete();
						} else if (res.cancel) {
							console.log('用户点击了取消');
						}
					}
				});
			},
			// 删除
			confirmDelete() {
				this.$dbUtils.delData('testDb', 'scores', {
						week: this.deleteWeek
					})
					.then(response => {
						console.log("删除成功:", response);
						// 成功后可以刷新列表或做其他操作
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						this.deleteDialog = false;
						// 假设你有一个方法来重新加载学生列表
						this.getData();
					})
					.catch(error => {
						console.error("删除失败:", error);
						uni.showToast({
							title: '删除失败，请稍后再试',
							icon: 'none'
						});
					});
			},
			goPerson(student) {
				console.log("去个人中心");
				uni.setStorageSync(student.name, student);
				uni.setStorageSync('周数', this.weeks);
				uni.navigateTo({
					url: '/pages/index/person?name=' + student.name,
					animationType: 'fade-in',
					animationDuration: 200
				});
			},
			// 确认导入
			confirmImport() {
				console.log('正在访问:', this.importLink.url);
				// 访问链接获取数据的逻辑
				this.fetchAndParseExcel(this.importLink.url);
				this.importDialog = false
			},
			fetchAndParseExcel(url) {
				// 使用 uni.request 下载文件
				uni.request({
					url: url,
					method: 'GET',
					responseType: 'arraybuffer', // 确保以二进制格式接收文件
					success: (res) => {
						if (res.statusCode === 200) {
							// 下载成功，开始解析文件
							this.parseExcel(res.data);
						} else {
							console.error('文件下载失败:', res.statusCode);
						}
					},
					fail: (err) => {
						console.error('请求失败:', err);
					},
				});
			},
			// 解析 Excel 数据
			async parseExcel(data) {
				try {
					// 将二进制数据转换为工作簿对象
					const workbook = XLSX.read(data, {
						type: 'array'
					});

					// 选择要解析的工作表（假设是第一个工作表）
					const worksheet = workbook.Sheets[workbook.SheetNames[0]];

					// 将工作表转换为 JSON 格式（数组）
					const jsonData = XLSX.utils.sheet_to_json(worksheet, {
						header: 1
					}); // header: 1 表示使用第一行作为列标题

					let students = [];

					// 遍历 Excel 数据（从第二行开始，第一行通常是表头）
					for (let row of jsonData.slice(1)) {
						const name = row[0]; // 姓名
						const score = (row[1] !== undefined && row[1] !== null && !isNaN(row[1]) && !/[\u4e00-\u9fa5]/
								.test(row[1])) ?
							parseInt(row[1], 10) : 0; // 成绩

						// 根据姓名查询数据库，获取 student_id
						try {
							const results = await this.$dbUtils.selectDataLike('testDb', 'students', 'name', name);
							if (results.length > 0) {
								const studentId = results[0].student_id; // 获取查询结果中的 student_id

								// 将数据添加到 students 数组中
								students.push({
									name: name, // 姓名
									score: score, // 成绩
									student_id: studentId, // 学号
									week: this.importLink.week, // 周数
								});
							} else {
								console.warn(`未找到姓名为 ${name} 的学生`);
							}
						} catch (error) {
							console.error(`查询姓名为 ${name} 的学生时出错:`, error);
						}
					}

					// 插入数据时显示加载图标
					console.log('===转换后的学生数据===:' + students);
					// 排序学生成绩，从高到低
					students.sort((a, b) => b.score - a.score);

					// 给学生添加排名
					students.forEach((student, index) => {
						// 处理成绩相同的学生，赋予相同排名
						if (index > 0 && students[index].score === students[index - 1].score) {
							student.class_rank = students[index - 1].class_rank;
						} else {
							student.class_rank = index + 1; // 排名从1开始
						}
					});

					console.log("==处理好的数组==:", students);
					// 确保 both 为数字类型
					if (this.weeks.includes(Number(this.importLink.week))) {
						// 更新数据到数据库
						for (const item of students) {
							await this.$dbUtils.updateSQLMore(
								'testDb',
								'scores', {
									score: item.score,
									class_rank: item.class_rank
								}, // 只更新分数
								['student_id', 'week'], // 条件字段
								[item.student_id, item.week] // 对应的条件值
							);
						}
						uni.showToast({
							title: '更新成功',
							icon: 'success'
						});
						// console.log("更新成功");
					} else {
						// 插入数据到数据库
						for (const item of students) {
							await this.$dbUtils.addTabItem('testDb', 'scores', item);
						}
						uni.showToast({
							title: '插入成功',
							icon: 'success'
						});
						// console.log("插入成功")
					}

					this.getData();
				} catch (error) {
					console.error('Excel 解析失败:', error);
				}
			},
			// 清空时刷新
			onClear() {
				console.log('搜索框已清空');
				// 清空时执行查询的方法
				this.getData();
			},
			// 模拟搜索
			performSearch() {
				// 模拟搜索逻辑
				const value = this.keyword;
				if (value) {
					console.log(`正在搜索关键词: ${value}`);
					this.$dbUtils.selectDataLike('testDb', 'scores', 'name', value)
						.then(results => {
							console.log("模糊查询成功:", results);

							// Step 1: Group by student_id and name
							let groupedData = {};
							results.forEach(record => {
								if (!groupedData[record.student_id]) {
									groupedData[record.student_id] = {
										student_id: record.student_id,
										name: record.name,
										weeks: []
									};
								}
								groupedData[record.student_id].weeks.push({
									week: record.week,
									score: record.score,
									ranking: record.class_rank // 直接使用数据库中的排名
								});
							});

							// Convert to array for easier manipulation
							let studentsArray = Object.values(groupedData);

							// Extract unique weeks from the results
							let weeks = Array.from(new Set(results.map(s => s.week))).sort((a, b) => a - b);

							// 更新组件状态
							this.students = studentsArray;
							this.weeks = weeks;
							console.log("查询学生:", this.students);
							console.log("查询周数:", this.weeks);

						})
						.catch(error => {
							console.error("模糊查询失败:", error);
						});
				} else {
					console.warn('请输入搜索关键词');
				}
			},
			// 获取数据
			async getData() {
				try {
					const results = await this.$dbUtils.selectDataList('testDb', 'scores', {});
					console.log("查询成功:", results);

					// Step 1: Group by student_id and name
					let groupedData = {};
					results.forEach(record => {
						if (!groupedData[record.student_id]) {
							groupedData[record.student_id] = {
								student_id: record.student_id,
								name: record.name,
								weeks: []
							};
						}
						groupedData[record.student_id].weeks.push({
							week: record.week,
							score: record.score,
							ranking: record.class_rank // 直接使用数据库中的排名
						});
					});

					// Convert to array for easier manipulation
					let studentsArray = Object.values(groupedData);

					// Extract unique weeks from the results
					let weeks = Array.from(new Set(results.map(s => s.week))).sort((a, b) => a - b);

					// 更新组件状态
					this.students = studentsArray;
					this.weeks = weeks;
					console.log("查询学生:", this.students);
					console.log("查询周数:", this.weeks);

				} catch (error) {
					console.error("查询失败:", error);
				}
			},
			getScore(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.score : '-';
			},
			getRanking(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.ranking : '-';
			},
		}
	};
</script>
<style scoped>
	.container {
		padding: 20rpx;
	}

	.action-buttons {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
		display: flex;
		flex-direction: row;
		/* 默认是row，可省略 */
		justify-content: space-between;
		/* 根据需要调整对齐方式 */
		gap: 10px;
		/* 按钮之间的间距 */
	}

	.student-table {
		margin-top: 20rpx;
	}

	.form-content {
		padding: 20rpx;
	}

	.delete-content {
		text-align: center;
		padding: 20rpx;
	}

	.uni-group {
		display: flex;
		align-items: center;
	}

	.u-page {
		padding: 0;
	}

	.u-cell-icon {
		width: 36rpx;
		height: 36rpx;
		margin-right: 8rpx;
	}

	.u-cell-group__title__text {
		font-weight: bold;
	}
</style>